<script setup lang="ts">
import { h } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NCard, NDataTable, NPagination, NPopconfirm, NSpace, NTag } from 'naive-ui'
import { useBoolean } from '@/hooks'
import { fetchAllDrivers, fetchDeviceTypeList, deleteDeviceType } from '@/service/api/deviceType'
import DeviceTypeModal from './components/DeviceTypeModal.vue'
import LuaEditorModal from './components/LuaEditorModal.vue'
import ProtocolTestModal from './components/ProtocolTestModal.vue'
import NovaIcon from '@/components/common/NovaIcon.vue'

defineOptions({ name: 'DeviceTypeList' })

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)

const listData = ref<Api.DeviceType.Info[]>([])

const model = ref({
  name: '',
})

const initialModel = { ...model.value }

// 可用的协议列表
const availableDrivers = ref<string[]>([])

// 模态框相关
const visible = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const modalData = ref<Api.DeviceType.Info | null>(null)

// Lua 编辑器模态框
const luaEditorVisible = ref(false)
const currentDriver = ref('')

// 协议测试模态框
const protocolTestVisible = ref(false)
const testDriver = ref('')

const pagination = reactive({
  page: 1,
  pageSize: 20,
  pageCount: 0,
  itemCount: 0,
})

onMounted(() => {
  getDeviceTypeList()
  loadAvailableDrivers()
})

async function getDeviceTypeList() {
  try {
    startLoading()
    const { isSuccess, data } = await fetchDeviceTypeList({
      page: pagination.page,
      pageSize: pagination.pageSize,
    } as any)
    if (isSuccess && data) {
      listData.value = data.lists || []
      pagination.itemCount = data.count || 0
      pagination.pageCount = Math.ceil(pagination.itemCount / pagination.pageSize)
    }
  }
  catch (e: any) {
    window.$message.error(e.message || '获取设备类型列表失败')
  }
  finally {
    endLoading()
  }
}

async function loadAvailableDrivers() {
  try {
    const { isSuccess, data } = await fetchAllDrivers()
    if (isSuccess && data) {
      availableDrivers.value = data
    }
  }
  catch (e: any) {
    console.error('加载协议列表失败:', e)
  }
}

function handlePageChange(page: number) {
  pagination.page = page
  getDeviceTypeList()
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize
  pagination.page = 1
  getDeviceTypeList()
}

function handleResetSearch() {
  model.value = { ...initialModel }
  pagination.page = 1
  getDeviceTypeList()
}

function handleSearch() {
  pagination.page = 1
  getDeviceTypeList()
}

function handleAdd() {
  modalType.value = 'add'
  modalData.value = null
  visible.value = true
}

function handleEdit(row: Api.DeviceType.Info) {
  modalType.value = 'edit'
  modalData.value = row
  visible.value = true
}

function handleEditLua(driver: string) {
  if (!driver) {
    window.$message.warning('该设备类型未配置协议')
    return
  }
  currentDriver.value = driver
  luaEditorVisible.value = true
}

function handleTestProtocol(driver: string) {
  if (!driver) {
    window.$message.warning('该设备类型未配置协议')
    return
  }
  testDriver.value = driver
  protocolTestVisible.value = true
}

async function handleDelete(name: string) {
  try {
    const { isSuccess } = await deleteDeviceType(name)
    if (isSuccess) {
      window.$message.success('删除成功')
      getDeviceTypeList()
    }
  }
  catch (e: any) {
    window.$message.error(e.message || '删除失败')
  }
}

function handleModalSuccess() {
  visible.value = false
  getDeviceTypeList()
}

const columns: DataTableColumns<Api.DeviceType.Info> = [
  {
    title: '名称',
    align: 'center',
    key: 'name',
    width: 200,
  },
  {
    title: '协议/驱动',
    align: 'center',
    key: 'driver',
    width: 180,
    render: (row: Api.DeviceType.Info) => {
      return row.driver ? h(NTag, { type: 'info' }, { default: () => row.driver }) : '-'
    },
  },
  {
    title: '属性数量',
    align: 'center',
    key: 'properties',
    width: 120,
    render: (row: Api.DeviceType.Info) => {
      return row.properties?.length || 0
    },
  },
  {
    title: '更新时间',
    align: 'center',
    key: 'updatedAt',
    width: 180,
    render: (row: Api.DeviceType.Info) => {
      return row.updatedAt ? new Date(row.updatedAt * 1000).toLocaleString() : '-'
    },
  },
  {
    title: '操作',
    align: 'center',
    key: 'actions',
    width: 280,
    render: (row: Api.DeviceType.Info) => {
      const buttons: any[] = []
      
      if (row.driver) {
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleEditLua(row.driver!),
          }, { default: () => '编辑Lua' }),
        )
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'info',
            secondary: true,
            onClick: () => handleTestProtocol(row.driver!),
          }, { default: () => '测试协议' }),
        )
      }
      
      buttons.push(
        h(NButton, {
          size: 'small',
          onClick: () => handleEdit(row),
        }, { default: () => '编辑' }),
      )
      
      buttons.push(
        h(NPopconfirm, {
          onPositiveClick: () => handleDelete(row.name),
        }, {
          default: () => '确认删除？',
          trigger: () => h(NButton, { size: 'small', type: 'error' }, { default: () => '删除' }),
        }),
      )
      
      return h(NSpace, { justify: 'center' }, { default: () => buttons })
    },
  },
]
</script>

<template>
  <div class="h-full flex flex-col gap-16px overflow-hidden">
    <NCard title="设备类型管理" :bordered="false" size="small" class="flex-1 overflow-hidden">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <template #icon>
            <NovaIcon icon="icon-park-outline:add-one" />
          </template>
          新建类型
        </NButton>
      </template>

      <div class="h-full flex flex-col">
        <!-- 搜索栏 -->
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NButton size="small" type="primary" @click="handleSearch">
              <template #icon>
                <NovaIcon icon="icon-park-outline:search" />
              </template>
              搜索
            </NButton>
            <NButton size="small" @click="handleResetSearch">
              <template #icon>
                <NovaIcon icon="icon-park-outline:redo" />
              </template>
              重置
            </NButton>
          </NSpace>
        </NSpace>

        <!-- 数据表格 -->
        <div class="flex-1 min-h-0">
        <NDataTable
          :columns="columns"
          :data="listData"
          :loading="loading"
          :scroll-x="1000"
            :max-height="600"
        />
        </div>

        <!-- 分页 -->
        <div class="flex justify-end pt-16px">
          <NPagination
            v-model:page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-count="pagination.pageCount"
            :item-count="pagination.itemCount"
            size="small"
            show-quick-jumper
            show-size-picker
            :page-sizes="[10, 20, 50, 100]"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>
      </div>
    </NCard>

    <!-- 添加/编辑模态框 -->
    <DeviceTypeModal
      v-model:visible="visible"
      :type="modalType"
      :modal-data="modalData"
      :available-drivers="availableDrivers"
      @success="handleModalSuccess"
    />

    <!-- Lua 编辑器模态框 -->
    <LuaEditorModal
      v-model:visible="luaEditorVisible"
      :driver="currentDriver"
    />

    <!-- 协议测试模态框 -->
    <ProtocolTestModal
      v-model:visible="protocolTestVisible"
      :driver="testDriver"
    />
  </div>
</template>

<style scoped></style>

